from datetime import datetime, timedelta
from django.shortcuts import render
from rest_framework import viewsets
from rest_framework.response import Response
from rest_framework.filters import SearchFilter
from rest_framework.pagination import PageNumberPagination, LimitOffsetPagination
from django_filters.rest_framework import DjangoFilterBackend

from iClouds.Permissions import AllPermissions, MyPermissions
from iClouds.Authentication import MyJWTAuthentication
from iClouds.mktoken import get_tokens_for_user

from allinpay.serializers import AlertSerializer, AllOrderSerializer
from mysqldb.reconf import settlConf
from .serializers import *


class AllinpayQueryInListViewSet(viewsets.ModelViewSet):
    __title__ = "收单统计"
    __group__ = "聚合收单"
    __doc__ = """
    list:\n
    <h4>收单账单查询接口</h4>
    `根据账单查账，支持模糊查询`\n
    返回数据:\n
        "ali": "支付宝",
        "wx":"微信",
        "count": 12, 数据条数
        "trxamt": 12, 金额合计
        "fee": 0   手续费合计
    retrieve:\n
    <h4>收单账单详情接口</h4>
    `根据账单ID查询账单详情`\n
    """
    http_method_names = ["get"]
    authentication_classes = [MyJWTAuthentication]
    permission_classes = [MyPermissions]
    serializer_class = AlertSerializer
    pagination_class = PageNumberPagination
    queryset = AllinpayReceiptList.objects.all()
    # GET 条件过滤
    filter_backends = [DjangoFilterBackend, SearchFilter]
    filterset_class = AllinpayQueryInListFilterSet
    # filterset_fields = ["pid", "tid"]
    search_fields = ["cusorderid"]

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        A = (
            queryset.filter(trxstatus="0000", trxcode="VSP511")
            .values("cusorderid")
            .distinct()
            .aggregate(count=Count("id"), trxamt=Sum("trxamt"), fee=Sum("fee"))
        )
        V = (
            queryset.filter(trxstatus="0000", trxcode="VSP501")
            .values("cusorderid")
            .distinct()
            .aggregate(count=Count("id"), trxamt=Sum("trxamt"), fee=Sum("fee"))
        )
        return Response({"rescode": 200, "resmsg": serializer.data, "ali": A, "wx": V})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})


class AllinpayQueryOutListViewSet(viewsets.ModelViewSet):
    __title__ = "退单统计"
    __group__ = "聚合收单"
    __doc__ = """
    list:\n
    <h4>退款账单查询接口</h4>
    `根据账单查账，支持模糊查询`\n
    返回数据:\n
        "ali": "支付宝",
        "wx":"微信",
        "count": 12, 数据条数
        "trxamt": 12, 金额合计
        "fee": 0   手续费合计
    retrieve:\n
    <h4>退款账单详情接口</h4>
    `根据账单ID查询账单详情`\n
    """
    http_method_names = ["get"]
    authentication_classes = [MyJWTAuthentication]
    permission_classes = [MyPermissions]
    serializer_class = AllOrderSerializer
    pagination_class = PageNumberPagination
    queryset = AllinpayCancelList.objects.all()
    # GET 条件过滤
    filter_backends = [DjangoFilterBackend, SearchFilter]
    filterset_class = AllinpayQueryOutListFilterSet
    # filterset_fields = ["pid", "tid"]
    search_fields = ["reqsn", "oldreqsn"]

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        A = (
            queryset.filter(trxstatus="0000", trxcode="VSP511")
            .values("reqsn")
            .distinct()
            .aggregate(count=Count("id"), trxamt=Sum("trxamt"), fee=Sum("fee"))
        )
        V = (
            queryset.filter(trxstatus="0000", trxcode="VSP501")
            .values("reqsn")
            .distinct()
            .aggregate(count=Count("id"), trxamt=Sum("trxamt"), fee=Sum("fee"))
        )
        return Response({"rescode": 200, "resmsg": serializer.data, "ali": A, "wx": V})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})


class AllinpaySettlementReqstViewSet(viewsets.ModelViewSet):
    __title__ = "结算请求"
    __group__ = "聚合收单"
    __doc__ = """
    list:\n
    <h4>结算请求</h4>
    retrieve:\n
    <h4>结算请求</h4>
    根据记录ID查询账单详情\n
    create:\n
    <h4>创建结算请求</h4>
    请求参数:\n
        None:  创建全部场所结算
        pid:   创建指定场所结算
        tid:   创建指定名目结算
    """
    http_method_names = ["get", "post"]
    authentication_classes = [MyJWTAuthentication]
    permission_classes = [MyPermissions]
    serializer_class = SettlementPostSerializer
    queryset = AllinpaySettlementList.objects.all()
    # GET 条件过滤
    filter_backends = [DjangoFilterBackend]
    filterset_class = AllinpaySettleListFilterSet
    # filterset_fields = ["pid", "tid"]
    # search_fields = ["cusorderid"]

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        # 创建时间戳
        lastday = (datetime.now() - timedelta(days=1)).strftime("%Y%m%d")
        today = datetime.now().strftime("%Y%m%d")
        # 最小结算金额
        settl = settlConf()
        mix_money = settl.min_value
        # 创建结算对象
        queue = []
        req = serializer.data["bind"]
        for pid, tid, fee, trxdate in req:
            # 定义数据筛选器
            filters = {
                "pid": pid,
                "tid": tid,
                "trxstatus": "0000",
                "trxdate__lt": today,
            }
            filterc = {
                "pid": pid,
                "tid": tid,
                "trxstatus": "0000",
                "fintime__lt": today + "000000",
            }
            if trxdate:
                filters["trxdate__gt"] = trxdate
                filterC["fintime__gt"] = trxdate + "000000"
            # 基础数据
            queryset = {
                "pid": pid,
                "tid": tid,
                "trxdate": lastday,
                "creattime": timezone.now(),
            }
            # 统计收单
            queryset.update(
                AllinpayReceiptList.objects.filter(**filters).aggregate(
                    acount=Count("id"),
                    amoney=Sum("trxamt", default=0),
                    afee=Sum("fee", default=0),
                )
            )
            # 统计退款
            queryset.update(
                AllinpayCancelList.objects.filter(**filterc).aggregate(
                    ocount=Count("id"),
                    omoney=Sum("trxamt", default=0),
                    ofee=Sum("fee", default=0),
                )
            )
            # 平台手续费
            queryset.update(
                {
                    "myfee": (queryset.get("amoney", 0) - queryset.get("omoney", 0))
                    * float(fee)
                    / 100,
                }
            )
            # 加入数据队列
            if (queryset["amoney"] - queryset["omoney"]) < mix_money:
                continue
            queue.append(queryset)

        # if not queue:
        #     raise serializers.ValidationError({"Settlement": "没有结算记录"})
        serializer = AllinpaySettlementAutoSerializer(data=queue, many=True)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(
            {"rescode": 200, "resmsg": {"Settlement": f"{len(serializer.data)} 条结算记录"}}
        )


class AllinpaySettlementVlidViewSet(viewsets.ModelViewSet):
    __title__ = "结算审核"
    __group__ = "聚合收单"
    __doc__ = """
    create:\n
    <h4>创建结算审核</h4>
    """
    http_method_names = ["post"]
    authentication_classes = [MyJWTAuthentication]
    permission_classes = [MyPermissions]
    serializer_class = AllinpaySettlementVlidSerializer
    queryset = AllinpaySettlementList.objects.all()

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        instance = self.queryset.get(id=serializer.data["id"])
        instance.is_vlid = serializer.data.get("is_vlid")
        instance.save()
        return Response({"rescode": 200, "resmsg": self.get_serializer(instance).data})


class AllinpayPayBankViewSet(viewsets.ModelViewSet):
    __title__ = "结算打款"
    __group__ = "聚合收单"
    __doc__ = """
    list:\n
    <h4>结算打款</h4>
    retrieve:\n
    <h4>结算打款</h4>
    根据记录ID查询账单详情\n
    create:\n
    <h4>结算打款</h4>
    """
    http_method_names = ["get", "post"]
    authentication_classes = [MyJWTAuthentication]
    permission_classes = [MyPermissions]
    serializer_class = allinpaySettlementBankSerializer
    queryset = AllinpaySettlementBank.objects.all()
    # GET 条件过滤
    # filter_backends = [DjangoFilterBackend]
    # filterset_class = AllinpayQueryInListFilterSet
    # filterset_fields = ["pid", "tid"]
    # search_fields = ["cusorderid"]
    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})


# 检查视图
from iClouds.apidev import filter_views

filter_views(globals())
